<?php
namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\YuanfenjuService;
use app\common\model\ZiweiLiupanLog;

/**
 * 紫微流盘接口
 * @ApiWeigh (90)
 */
class ZiweiLiupan extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = '*';

    /**
     * 紫微流盘排盘
     * 
     * @ApiTitle    (紫微流盘排盘)
     * @ApiSummary  (根据用户信息进行紫微流盘排盘分析)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/ziwei_liupan/index)
     * 
     * @ApiParams   (name="name", type="string", required=true, description="姓名")
     * @ApiParams   (name="sex", type="integer", required=true, description="性别：0=男，1=女")
     * @ApiParams   (name="type", type="integer", required=true, description="历类型：0=农历，1=公历")
     * @ApiParams   (name="year", type="integer", required=true, description="出生年，如：1988")
     * @ApiParams   (name="month", type="integer", required=true, description="出生月，如：8")
     * @ApiParams   (name="day", type="integer", required=true, description="出生日，如：7")
     * @ApiParams   (name="hours", type="integer", required=true, description="出生时，如：12")
     * @ApiParams   (name="minute", type="integer", required=false, description="出生分，如：30")
     * @ApiParams   (name="leap_bound", type="integer", required=false, description="闰月分界：0=月中分界,1=做下月", default=0)
     * @ApiParams   (name="pros_cons", type="integer", required=false, description="长生顺逆：1=全部顺排,2=按年干阴阳,3=按照男女", default=2)
     * @ApiParams   (name="pan_model", type="integer", required=false, description="盘类型：0=先天盘+大限盘,1=流年盘,2=流月盘,3=流日盘,4=流时盘", default=0)
     * @ApiParams   (name="dx_model", type="integer", required=false, description="大限顺逆：1=阳男阴女顺阴女阳男逆,2=男顺女逆", default=1)
     * @ApiParams   (name="liu_time", type="string", required=false, description="流年、月、日时的时间戳，如：1698805691")
     * @ApiParams   (name="sect", type="integer", required=false, description="流派：1=晚子时日柱算明天,2=晚子时日柱算当天", default=2)
     * @ApiParams   (name="zhen", type="integer", required=false, description="是否真太阳时：1=考虑真太阳时,2=不考虑真太阳时", default=2)
     * @ApiParams   (name="province", type="string", required=false, description="省份，如：北京市")
     * @ApiParams   (name="city", type="string", required=false, description="城市，如：北京")
     * 
     * @ApiReturn   ({
       "code": 1,
       "msg": "获取成功",
       "time": "1677123456",
       "data": {
         "base_info": {                    // 基本信息
           "name": "张三",                 // 姓名
           "sex": "男",                    // 性别
           "gongli": "1988-08-07 12:30",   // 公历时间
           "nongli": "戊辰年六月廿五日"    // 农历时间
         },
         "pan_info": {                     // 盘面信息
           "ming_gong": "寅",              // 命宫
           "shen_gong": "午",              // 身宫
           "stars": [...],                 // 星曜信息
           "palaces": [...]                // 宫位信息
         }
       }
     })
     */
    public function index()
    {
        $params = [
            'name' => $this->request->post('name', ''),
            'sex' => $this->request->post('sex', 0, 'intval'),
            'type' => $this->request->post('type', 0, 'intval'),
            'year' => $this->request->post('year', '', 'intval'),
            'month' => $this->request->post('month', '', 'intval'),
            'day' => $this->request->post('day', '', 'intval'),
            'hours' => $this->request->post('hours', '', 'intval'),
            'minute' => $this->request->post('minute', null, 'intval'),
            'leap_bound' => $this->request->post('leap_bound', 0, 'intval'),
            'pros_cons' => $this->request->post('pros_cons', 2, 'intval'),
            'pan_model' => $this->request->post('pan_model', 0, 'intval'),
            'dx_model' => $this->request->post('dx_model', 1, 'intval'),
            'liu_time' => $this->request->post('liu_time', ''),
            'sect' => $this->request->post('sect', 2, 'intval'),
            'zhen' => $this->request->post('zhen', 2, 'intval'),
            'province' => $this->request->post('province', ''),
            'city' => $this->request->post('city', '')
        ];

        // 必填参数验证
        $required = ['name', 'sex', 'type', 'year', 'month', 'day', 'hours'];
        foreach ($required as $field) {
            if (!isset($params[$field])) {
                $this->error(__('Parameter %s can not be empty', $field));
            }
        }

        // 参数验证
        if (!in_array($params['sex'], [0, 1])) {
            $this->error(__('Invalid sex value'));
        }
        if (!in_array($params['type'], [0, 1])) {
            $this->error(__('Invalid type value'));
        }
        if ($params['pan_model'] < 0 || $params['pan_model'] > 4) {
            $this->error(__('Invalid pan_model value'));
        }
        if (!in_array($params['dx_model'], [1, 2])) {
            $this->error(__('Invalid dx_model value'));
        }

        try {
            $result = YuanfenjuService::instance()->request('/Liupan/zwlpan', $params);
            
            if ($result['errcode'] != 0) {
                $this->error($result['errmsg'] ?? '紫微流盘排盘分析失败');
            }
            
            // 记录查询日志
            ZiweiLiupanLog::create(array_merge(
                $params,
                [
                    'user_id' => $this->auth->id,
                    'response_data' => json_encode($result['data'], JSON_UNESCAPED_UNICODE)
                ]
            ));
            
            $this->success('获取成功', $result['data']);
            
        } catch (\think\exception\PDOException $e) {
            $this->error('服务异常：' . $e->getMessage());
        }
    }

    /**
     * 查询历史列表
     * 
     * @ApiTitle    (紫微流盘历史记录)
     * @ApiSummary  (获取用户的紫微流盘查询历史记录)
     * @ApiMethod   (GET)
     * @ApiRoute    (/api/ziwei_liupan/history)
     * @ApiParams   (name="page", type="integer", required=false, description="页码", default=1)
     * @ApiParams   (name="limit", type="integer", required=false, description="每页数量", default=10)
     * 
     * @ApiReturn   ({
       "code": 1,
       "msg": "获取成功",
       "time": "1677123456",
       "data": {
         "total": 100,                     // 总记录数
         "list": [{
           "id": 1,                        // 记录ID
           "name": "张三",                 // 姓名
           "sex": 0,                       // 性别
           "sex_text": "男",               // 性别文字
           "type": 1,                      // 历类型
           "type_text": "公历",            // 历类型文字
           "year": 1988,                   // 年
           "month": 8,                     // 月
           "day": 7,                       // 日
           "hours": 12,                    // 时
           "createtime": 1677123456,       // 创建时间戳
           "createtime_text": "2023-02-23 12:34:56" // 创建时间文字
         }]
       }
     })
     */
    public function history()
    {
        $page = $this->request->get('page', 1, 'intval');
        $limit = $this->request->get('limit', 10, 'intval');
        
        $total = ZiweiLiupanLog::where('user_id', $this->auth->id)->count();
        $list = ZiweiLiupanLog::where('user_id', $this->auth->id)
            ->field('id,name,sex,type,year,month,day,hours,createtime,minute,leap_bound,pros_cons,pan_model,dx_model,liu_time,sect,zhen,province,city')
            ->order('id desc')
            ->page($page, $limit)
            ->select();
        
        $this->success('获取成功', [
            'total' => $total,
            'list' => $list
        ]);
    }

    /**
     * 查询历史详情
     * 
     * @ApiTitle    (紫微流盘历史详情)
     * @ApiSummary  (获取指定紫微流盘记录的详细信息)
     * @ApiMethod   (GET)
     * @ApiRoute    (/api/ziwei_liupan/detail)
     * @ApiParams   (name="id", type="integer", required=true, description="记录ID")
     * 
     * @ApiReturn   ({
       "code": 1,
       "msg": "获取成功",
       "time": "1677123456",
       "data": {
         "id": 1,                          // 记录ID
         "user_id": 1,                     // 用户ID
         "name": "张三",                   // 姓名
         "sex": 0,                         // 性别
         "sex_text": "男",                 // 性别文字
         "type": 1,                        // 历类型
         "type_text": "公历",              // 历类型文字
         "year": 1988,                     // 年
         "month": 8,                       // 月
         "day": 7,                         // 日
         "hours": 12,                      // 时
         "minute": 30,                     // 分
         "leap_bound": 0,                  // 闰月分界
         "leap_bound_text": "月中分界",    // 闰月分界文字
         "pros_cons": 2,                   // 长生顺逆
         "pros_cons_text": "按年干阴阳",   // 长生顺逆文字
         "pan_model": 0,                   // 盘类型
         "pan_model_text": "先天盘+大限盘", // 盘类型文字
         "dx_model": 1,                    // 大限顺逆
         "dx_model_text": "阳男阴女顺阴女阳男逆", // 大限顺逆文字
         "liu_time": "1698805691",         // 流盘时间戳
         "sect": 2,                        // 流派
         "sect_text": "晚子时日柱算当天",  // 流派文字
         "zhen": 2,                        // 是否真太阳时
         "zhen_text": "不考虑真太阳时",    // 真太阳时文字
         "province": "北京市",             // 省份
         "city": "北京",                   // 城市
         "createtime": 1677123456,         // 创建时间戳
         "createtime_text": "2023-02-23 12:34:56", // 创建时间文字
         "response_data": {                // 原始接口返回数据
           // ... 同紫微流盘接口返回的data部分
         }
       }
     })
     */
    public function detail()
    {
        $id = $this->request->get('id', 0, 'intval');
        
        $log = ZiweiLiupanLog::where('user_id', $this->auth->id)
            ->where('id', $id)
            ->find();
            
        if (!$log) {
            $this->error('记录不存在');
        }
        
        $log['response_data'] = json_decode($log['response_data'], true);
        
        $this->success('获取成功', $log);
    }

    /**
     * 清空历史记录
     * 
     * @ApiTitle    (清空紫微流盘历史记录)
     * @ApiSummary  (清空当前用户的所有紫微流盘查询记录)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/ziwei_liupan/clearHistory)
     * 
     * @ApiReturn   ({
     *   "code": 1,
     *   "msg": "清空成功",
     *   "data": null
     * })
     */
    public function clearHistory()
    {
        try {
            ZiweiLiupanLog::where('user_id', $this->auth->id)->delete();
            $this->success('清空成功');
        } catch (\think\exception\PDOException $e) {
            $this->error('清空失败：' . $e->getMessage());
        }
    }
}